package com.qf.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author wbzs,
 * @date 2022/10/27,
 * @time 22:11,
 */
public class zkTestMain {

    private CountDownLatch countDownLatch=new CountDownLatch(1);
    private ZooKeeper zk;
    @Before
    public void connection() throws Exception{
        //连接zk
         zk = new ZooKeeper("10.9.12.200:9096",1000, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                Watcher.Event.EventType type = watchedEvent.getType();//zk的事件类型
                Event.KeeperState state = watchedEvent.getState();//获取事件的状态
                String path = watchedEvent.getPath();//查看事件的路径

                System.err.println("zkTestMain中的方法process 执行了--->"+path);

                switch (type){
                    case None:    //和节点操作无关，主要是连接的状态
                        switch (state){
                            case SyncConnected:
                                System.err.println("连接成功");
                                countDownLatch.countDown();
                                break;
                        }

                }
            }
        });
        countDownLatch.await(); //阻塞当前线程，等待唤醒
    }

//创建节点
    @Test
    public void textX() throws Exception {

        //创建节点,返回节点就是我们创建的路径
        String gp13plus = zk.create("/gp13plus", "nihaozookeeper".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(gp13plus);

    }

    //获取数据
    @Test
    public void textX1() throws Exception {
        /*
        参数一：要获取数据的节点
        参数二：是不是开启监听，如果设置为true，当前节点在发生数据变化的时候就会触发监听
        参数三：获取数据的时候对节点的一些要求
         */
        byte[] data = zk.getData("/gp13plus", true, null);
        String s = new String(data);
        System.out.println(s);
    }

    //设置数据
    @Test
    public void textX2() throws Exception{
        //version 版本号，-1代表忽略version,否则必须和当前服务器上一样的version才能成功，这就是乐观锁
        Stat stat = zk.setData("/gp13plus", "这是新的数据".getBytes(), -1);

    }


    // 测试节点是否存在
    @Test
    public void textX3() throws Exception {
        //参数2：监听，如果当前节点不存在，设置为true,当节点存在的时候就会触发监听
        Stat gp13plus = zk.exists("gp13plus", true);
        System.out.println(gp13plus);
    }

    //删除节点
    @Test
    public void textX4() throws Exception{
    zk.delete("/gp13plus",-1);
    }
}
